package com.jnshu.security.authentication;

import com.jnshu.pojo.ZuulManage;
import com.jnshu.service.AdminService;
import com.jnshu.tools.binding.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author xmp
 * @date 2019/8/16 15:59
 */
@Service
@Slf4j
public class CustomizeUserPermission implements UserDetailsService {
    @Autowired(required = false)
    AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        ZuulManage manageUser = adminService.selectManageByName(name);
        if (manageUser == null){
            throw new UsernameNotFoundException ("用户名不存在");
        }
        List<String> permissionList = adminService.selectRoleById(manageUser.getRoleId()).getPermissionList();
        log.info ("查询出来的角色为："+ JsonUtil.toJsonString (permissionList));
        for (String i : permissionList){
            log.info("角色："+i);
            authorities.add(new SimpleGrantedAuthority(i));
        }
        return new User(manageUser.getName(),manageUser.getPassword(),authorities);
    }
}
